<?php
/**
 *
 * User: 罗艳忠
 * Email:luozong05@126.com
 * DateTime: 2017/5/15 12:26
 */

namespace App\Http\Controllers;
use App\Models\WechatMaterial;
use App\Models\WechatMaterialMedia;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use Validator;

class MaterialController extends Controller
{
    public $wechatMaterialModel;
    public $wechatMaterialMediaModel;
    function __construct(Request $request, WechatMaterial $wechatMaterial, WechatMaterialMedia $wechatMaterialMedia){
        parent::__construct();
        $this->request = $request;
        $this->wechatMaterialModel = $wechatMaterial;
        $this->wechatMaterialMediaModel = $wechatMaterialMedia;
    }

    public function index(){
        $where = [];
        $this->data["materialList"]  = $this->wechatMaterialModel->where($where)->paginate(5);
        return $this->showView("material_index");
    }

    public function getremote(){
        $typename = $this->request->get("typename","news");
        $easyMaterial = \EasyWeChat::material();
        $list = $easyMaterial->lists($typename, 50, 5);
        //dd($list);
        $this->insertMedia($list['item'], $typename);

        for($i = 20; $i <= $list["total_count"]; $i = $i+20){
            $list = $easyMaterial->lists($typename, $i);
            $this->insertMedia($list['item'], $typename);
        }
    }

    private function insertMedia($dataList,$typename){
        if($typename != "news") {
            foreach ($dataList as $item) {
                $item["typename"] = $typename;
                if($file = file_get_contents($item["url"])){
                    $qrcode_url = "/material_thumb/" . md5($item["url"]) . ".jpg";
                    if (\Storage::put($qrcode_url, $file)) {

                    }
                }
                $this->wechatMaterialMediaModel->firstOrCreate($item);
            }
        }else{
            foreach ($dataList as $item) {
                $data["media_id"] = $item["media_id"];
                //var_dump($item["media_id"]);
                $data["update_time"] = $item["update_time"];
                if (isset($item["content"]["news_item"][0])) {
                    $data["content"] = $item["content"]["news_item"][0]["content"];
                    $data["title"] = $item["content"]["news_item"][0]["title"];
                    $data["author"] = $item["content"]["news_item"][0]["author"];
                    $data["digest"] = $item["content"]["news_item"][0]["digest"];
                    $data["thumb_media_id"] = $item["content"]["news_item"][0]["thumb_media_id"];
                    $data["url"] = $item["content"]["news_item"][0]["url"];
                    $data["thumb_url"] = $item["content"]["news_item"][0]["thumb_url"];
                }
                try {
                    $this->wechatMaterialModel->firstOrCreate($data);
                }catch (\Exception $exception){

                }
            }
        }
    }

}